// --------------------------------------------------------------------------------------------------------------------- 
// <copyright file="ExponentialMovingAverage.cs" company="Scrum for Team System">
//   None
// </copyright>
// <summary>
//   Defines the ExponentialMovingAverage type.
// </summary>
// ---------------------------------------------------------------------------------------------------------------------
namespace ScrumForTeamSystem.Metrics
{
    /// <summary>
    /// Exponential Moving Average model: uses the simple Moving Average to generate the first Trend line point.
    /// Thereafter, each Trend line point is a percent A of the current Data point added to percent B of the last Trend
    /// point, where A+B=100.
    /// </summary>
    internal class ExponentialMovingAverage : MovingAverage
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ExponentialMovingAverage"/> class.
        /// </summary>
        /// <param name="period">The number of days in the average.</param>
        public ExponentialMovingAverage(int period) : base(period)
        {
        }

        /// <summary>
        /// Overrides the base class to calculate the average differently. For the first Trend line point, uses the
        /// base class; thereafter uses
        /// e * d + (1 - e) * t
        /// where
        /// e is an exponent based on the period
        /// d is the current Data point
        /// t is the last Trend point
        /// </summary>
        /// <param name="index">The index.</param>
        /// <returns>An "average".</returns>
        protected override double? CalculateAverage(int index)
        {
            var exponent = 2 / (this.Period + 1.0d);
            return index + 1 == this.Period 
                           ? base.CalculateAverage(index) 
                           : (this.Data[index] * exponent) + (this.Trend[index - 1] * (1 - exponent));
        }
    }
}